<template>
  <div>
    <!-- 查询与操作按钮 -->
    <div class="card" style="margin-bottom: 5px; display: flex; align-items: center;">
      <el-input v-model="searchUserName" prefix-icon="Search" style="width: 240px; margin-right: 10px;" placeholder="请输入用户名查询"></el-input>
      <el-input v-model="searchRuleName" prefix-icon="Search" style="width: 240px; margin-right: 10px;" placeholder="请输入规则名称查询"></el-input>
      <el-button type="info" plain @click="loadTransactionsByFilters">查询</el-button>
      <el-button type="warning" plain @click="reset">重置</el-button>
    </div>

    <!-- ECharts 图表 -->
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>

    <!-- 订单列表 -->
    <el-table :data="transactions" border stripe style="width: 100%;" @sort-change="handleSortChange">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="userName" label="用户名" width="120"></el-table-column>
      <el-table-column prop="ruleName" label="规则名称" width="150"></el-table-column>
      <el-table-column prop="points" label="变动积分" sortable="custom" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.points > 0 ? 'green' : 'red' }">{{ scope.row.points }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="balance" label="变动后余额" width="120"></el-table-column>
      <el-table-column prop="type" label="类型" width="100">
        <template #default="scope">
          {{ formatType(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" sortable="custom" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" style="text-align: center; margin-top: 20px;">
      <el-pagination
          @current-change="handlePageChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="totalItems">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick} from 'vue';
import request from '@/utils/request.js'; // 确保这是你的axios封装
import * as echarts from 'echarts';

const transactions = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalItems = ref(0);
const searchUserName = ref('');
const searchRuleName = ref('');
const sortField = ref('');
const sortOrder = ref('');
const chartContainer = ref(null);

// 加载交易记录
const loadTransactions = async (pageNum = 1, userName = '', ruleName = '', sortField = '', sortOrder = '') => {
  try {
    const res = await request.get('/point/transaction/page', {
      params: {
        pageNum,
        pageSize: pageSize.value,
        userName,
        ruleName,
        sortField,
        sortOrder
      }
    });
    if (res.code === '200') {
      transactions.value = res.data.list || [];
      totalItems.value = res.data.total;
      updateChart(transactions.value);
    }
  } catch (error) {
    console.error('Failed to load transactions:', error);
  }
};

// 根据过滤条件加载交易记录
const loadTransactionsByFilters = () => {
  currentPage.value = 1; // 重置当前页为第一页
  loadTransactions(1, searchUserName.value, searchRuleName.value, sortField.value, sortOrder.value);
};

// 重置搜索条件
const reset = () => {
  searchUserName.value = '';
  searchRuleName.value = '';
  sortField.value = '';
  sortOrder.value = '';
  loadTransactions();
};

// 处理分页变化
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  loadTransactions(newPage, searchUserName.value, searchRuleName.value, sortField.value, sortOrder.value);
};

// 处理排序变化
const handleSortChange = ({column, prop, order}) => {
  sortField.value = prop;
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc';
  loadTransactions(currentPage.value, searchUserName.value, searchRuleName.value, sortField.value, sortOrder.value);
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化类型
const formatType = (type) => {
  switch (type) {
    case 1:
      return '赚取';
    case 2:
      return '消费';
    default:
      return '未知';
  }
};

// 更新ECharts图表
const updateChart = (data) => {
  const pointsData = {};
  data.forEach(item => {
    if (!pointsData[item.ruleName]) {
      pointsData[item.ruleName] = {earn: 0, consume: 0};
    }
    if (item.points > 0) {
      pointsData[item.ruleName].earn += item.points;
    } else {
      pointsData[item.ruleName].consume -= item.points;
    }
  });

  const ruleNames = Object.keys(pointsData);
  const earnSeries = ruleNames.map(ruleName => pointsData[ruleName].earn);
  const consumeSeries = ruleNames.map(ruleName => pointsData[ruleName].consume);

  nextTick(() => {
    const chart = echarts.init(chartContainer.value);
    chart.setOption({
      title: {
        text: '各规则名称下的积分获取和消费情况'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['获取', '消费']
      },
      xAxis: {
        type: 'category',
        data: ruleNames
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '获取',
          type: 'bar',
          stack: '总量',
          data: earnSeries,
          itemStyle: {
            color: '#5470c6'
          }
        },
        {
          name: '消费',
          type: 'bar',
          stack: '总量',
          data: consumeSeries,
          itemStyle: {
            color: '#91cc75'
          }
        }
      ]
    });
  });
};

// 初始化加载交易记录
onMounted(() => {
  console.log('Component mounted, loading transactions...');
  loadTransactions();
});
</script>

<style scoped>
.pagination {
  text-align: center;
  margin-top: 20px;
}
</style>



